<template>
  <div class="search">
    <Card>

      <Row @keydown.enter.native="handleSearch">
        <Form
            ref="searchForm"
            :label-width="70"
            :model="searchForm"
            class="search-form"
            inline
        >
          <Form-item label="商品名稱" prop="goodsName">
            <Input
                v-model="searchForm.goodsName"
                clearable
                placeholder="請輸入商品名稱"
                style="width: 200px"
                type="text"
            />
          </Form-item>
          <Form-item label="狀態" prop="status">
            <Select
                v-model="searchForm.marketEnable"
                clearable
                placeholder="請選擇"
                style="width: 200px"
            >
              <Option value="DOWN">下架</Option>
              <Option value="UPPER">上架</Option>
            </Select>
          </Form-item>
          <Form-item label="销售模式" prop="status">
            <Select
                v-model="searchForm.salesModel"
                clearable
                placeholder="請選擇"
                style="width: 200px"
            >
              <Option value="RETAIL">零售</Option>
              <Option value="WHOLESALE">批發</Option>
            </Select>
          </Form-item>
          <Form-item label="商品類型" prop="status">
            <Select
                v-model="searchForm.goodsType"
                clearable
                placeholder="請選擇"
                style="width: 200px"
            >
              <Option value="PHYSICAL_GOODS">实物商品</Option>
              <Option value="VIRTUAL_GOODS">虚拟商品</Option>
            </Select>
          </Form-item>
          <Form-item label="商品编號" prop="sn">
            <Input
                v-model="searchForm.id"
                clearable
                placeholder="商品编號"
                style="width: 200px"
                type="text"
            />
          </Form-item>
          <Button class="search-btn" type="primary" @click="handleSearch">搜索</Button>
          <Button class="search-btn" @click="handleReset">重置</Button>
        </Form>
      </Row>
      <Row class="operation padding-row">
        <Button type="primary" @click="addGoods">添加商品</Button>
        <Button type="primary" @click="openImportGoods">导入商品</Button>
        <Button type="primary" @click="viewWarnData">库存报表</Button>
        <Dropdown @on-click="handleDropdown">
          <Button type="default">
            批量操作
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="uppers">批量上架</DropdownItem>
            <DropdownItem name="lowers">批量下架</DropdownItem>
            <DropdownItem name="deleteAll">批量删除</DropdownItem>
            <DropdownItem name="batchShipTemplate">批量设置物流模板</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </Row>

      <Table
          ref="table"
          :columns="columns"
          :data="data"
          :loading="loading"
          border
          class="mt_10"
          @on-selection-change="changeSelect"
      >
        <!-- 商品栏目格式化 -->
        <template slot="goodsSlot" slot-scope="{ row }">
          <div style="margin-top: 5px; height: 90px; display: flex">
            <div style="">
              <img
                  :src="row.original"
                  style="height: 80px; margin-top: 3px; width: 70px"
              />
            </div>

            <div style="margin-left: 13px">
              <div class="div-zoom">
                {{ row.goodsName }}
                <!--                <a @click="linkTo(row.id, row.skuId)">{{ row.goodsName }}</a>-->
              </div>
              <!--              <Poptip title="掃碼在手機中查看" transfer trigger="hover">
                              <div slot="content">
                                &lt;!&ndash; <vueQr>123</vueQr> &ndash;&gt;
                                <vue-qr
                                    :margin="0"
                                    :size="150"
                                    :text="wapLinkTo(row.id, row.skuId)"
                                    colorDark="#000"
                                    colorLight="#fff"
                                ></vue-qr>
                              </div>
                              <img
                                  alt=""
                                  class="hover-pointer"
                                  height="20"
                                  src="../../../assets/qrcode.svg"
                                  width="20"
                              />
                            </Poptip>-->
            </div>
          </div>
        </template>
      </Table>
      <Row class="mt_10" justify="end" type="flex">
        <Page
            :current="searchForm.pageNumber"
            :page-size="searchForm.pageSize"
            :page-size-opts="[10, 20, 50]"
            :total="total"
            show-elevator
            show-sizer
            show-total
            size="small"
            @on-change="changePage"
            @on-page-size-change="changePageSize"
        ></Page>
      </Row>
    </Card>

    <Modal
        v-model="updateStockModalVisible"
        :mask-closable="false"
        :width="500"
        title="更新库存"
    >
      <Tabs value="updateStock">
        <TabPane label="手動规格更新" name="updateStock">
          <Table
              :columns="updateStockColumns"
              :data="stockList"
              border
              class="mt_10"
          ></Table>
        </TabPane>
        <TabPane label="批量规格更新" name="stockAll">
          <Input v-model="stockAllUpdate" placeholder="统一规格修改" type="number"/>
        </TabPane>
      </Tabs>

      <div slot="footer">
        <Button type="text" @click="updateStockModalVisible = false">取消</Button>
        <Button type="primary" @click="updateStock">更新</Button>
      </div>
    </Modal>

    <!-- 批量设置物流模板 -->
    <Modal
        v-model="shipTemplateModal"
        :mask-closable="false"
        :width="500"
        title="批量设置物流模板"
    >
      <Form ref="shipTemplateForm" :label-width="120" :model="shipTemplateForm">
        <FormItem class="form-item-view-el" label="物流模板" prop="templateId">
          <Select v-model="shipTemplateForm.templateId" style="width: 200px">
            <Option v-for="item in logisticsTemplate" :key="item.id" :value="item.id"
            >{{ item.name }}
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="shipTemplateModal = false">取消</Button>
        <Button type="primary" @click="saveShipTemplate">更新</Button>
      </div>
    </Modal>
    <Modal v-model="importModal" :mask-closable="false" title="导入商品信息">
      <div style="text-align: center">
        <Upload :action="action" :before-upload="handleUpload"
                :headers="accessToken"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                multiple name="files" type="drag">
          <div style="padding: 50px 0">
            <Icon size="102" style="color: #3399ff" type="ios-cloud-upload"></Icon>
            <h2>選擇或拖拽文件上傳</h2>
          </div>
          <Spin v-if="spinShow" fix></Spin>
        </Upload>
        <Button style="color: red" type="text" @click="exportGoods">下载导入模板</Button>
      </div>
      <div slot="footer">
        <Button type="text" @click="importModal = false">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  batchShipTemplate,
  deleteGoods,
  downLoadGoods,
  getGoodsListDataSeller,
  getGoodsSkuListDataSeller,
  getWarnData,
  lowGoods,
  selectsWarningStock,
  updateGoodsSkuStocks,
  upGoods
} from "@/api/goods";
import {baseUrl} from "@/libs/axios.js";
import * as API_Shop from "@/api/shops";

import {uploadGoodsExcel} from "../../../api/goods";

export default {
  name: "goods",
  data() {
    return {
      spinShow: false,
      accessToken: {}, // 驗證token
      importModal: false,
      action: baseUrl + "/goods/import/import", // 上傳接口
      id: "", //要操作的id
      loading: true, // 表單加载狀態
      shipTemplateForm: {}, // 物流模板
      shipTemplateModal: false, // 物流模板是否显示
      logisticsTemplate: [], // 物流列表
      updateStockModalVisible: false, // 更新库存模态框显隐
      stockAllUpdate: undefined, // 更新库存數量
      searchForm: {
        // 搜索框初始化对象
        pageNumber: 1, // 当前頁數
        pageSize: 10, // 頁面大小
        sort: "create_time", // 默认排序字段
        order: "desc", // 默认排序方式
      },
      stockList: [], // 库存列表
      form: {
        // 添加或编辑表單对象初始化數据
        goodsName: "",
        sn: "",
        marketEnable: "",
        price: "",
        sellerName: "",
      },
      updateStockColumns: [
        {
          title: "sku规格",
          key: "sn",
          minWidth: 120,
          render: (h, params) => {
            return h("div", {}, params.row.simpleSpecs);
          },
        },
        {
          title: "审核狀態",
          key: "authFlag",
          width: 130,
          render: (h, params) => {
            if (params.row.authFlag == "TOBEAUDITED") {
              return h("Tag", {props: {color: "blue"}}, "待审核");
            } else if (params.row.authFlag == "PASS") {
              return h("Tag", {props: {color: "green"}}, "通过");
            } else if (params.row.authFlag == "REFUSE") {
              return h("Tag", {props: {color: "red"}}, "审核拒绝");
            }
          },
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          render: (h, params) => {
            let vm = this;
            return h("InputNumber", {
              props: {
                value: params.row.quantity,
              },
              on: {
                "on-change": (event) => {
                  vm.stockList[params.index].quantity = event;
                },
              },
            });
          },
        },
      ],
      // 表單驗證规则
      formValidate: {},
      submitLoading: false, // 添加或编辑提交狀態
      selectList: [], // 多選數据
      selectCount: 0, // 多選计數
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "商品编號",
          key: "id",
          width: 180,
          tooltip: true,
        },
        {
          title: "商品名稱",
          key: "goodsName",
          minWidth: 200,
          slot: "goodsSlot",
        },
        {
          title: "销售模式",
          key: "salesModel",
          width: 100,
          render: (h, params) => {
            if (params.row.salesModel === "RETAIL") {
              return h("Tag", {props: {color: "orange"}}, "零售");
            } else if (params.row.salesModel === "WHOLESALE") {
              return h("Tag", {props: {color: "magenta"}}, "批發");
            } else {
              return h("Tag", {props: {color: "volcano"}}, "其他類型");
            }
          },
        },
        {
          title: "商品類型",
          key: "goodsType",
          width: 130,
          render: (h, params) => {
            if (params.row.goodsType === "PHYSICAL_GOODS") {
              return h("Tag", {props: {color: "geekblue"}}, "实物商品");
            } else if (params.row.goodsType === "VIRTUAL_GOODS") {
              return h("Tag", {props: {color: "purple"}}, "虚拟商品");
            } else {
              return h("Tag", {props: {color: "cyan"}}, "电子卡券");
            }
          },
        },
        /*{
          title: "商品價格",
          key: "price",
          width: 130,
          render: (h, params) => {
            return h("priceColorScheme", {props: {value: params.row.price, color: this.$mainColor}});
          },
        },*/
        {
          title: "商品價格",
          key: "price",
          width: 130,
          render: (h, params) => {
            const price = params.row.price;
            const formattedPrice = `HK$ ${price}`;
            const color = price > 100 ? 'red' : this.$mainColor;
            return h("span", {style: {color}}, formattedPrice);
          }
        },

        {
          title: "库存",
          key: "quantity",
          width: 120,
          render: (h, params) => {
            if (params.row.quantity > this.warnNum) {
              return h("Tag", {props: {color: "green"}}, params.row.quantity);
            } else if (params.row.quantity <= 0) {
              return h("Tag", {props: {color: "red"}}, 0);
            } else {
              return h("Tag", {props: {color: "red"}}, params.row.quantity);
            }
          },
        },
        {
          title: "审核狀態",
          key: "authFlag",
          width: 120,
          render: (h, params) => {
            if (params.row.authFlag == "PASS") {
              return h("Tag", {props: {color: "green"}}, "通过");
            } else if (params.row.authFlag == "TOBEAUDITED") {
              return h("Tag", {props: {color: "volcano"}}, "待审核");
            } else if (params.row.authFlag == "REFUSE") {
              return h("Tag", {props: {color: "red"}}, "审核拒绝");
            }
          },
        },
        {
          title: "上架狀態",
          key: "marketEnable",
          width: 130,
          sortable: false,
          render: (h, params) => {
            if (params.row.marketEnable == "DOWN") {
              return h("Tag", {props: {color: "red"}}, "下架");
            } else if (params.row.marketEnable == "UPPER") {
              return h("Tag", {props: {color: "green"}}, "上架");
            }
          },
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          fixed: "right",
          width: 200,
          render: (h, params) => {
            let enableOrDisable = "";
            let showEditStock = "";
            if (params.row.marketEnable == "DOWN") {
              enableOrDisable = h(
                  "Button",
                  {
                    props: {
                      size: "small",
                      type: "success",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.upper(params.row);
                      },
                    },
                  },
                  "上架"
              );
            } else {
              showEditStock = h(
                  "Button",
                  {
                    props: {
                      type: "default",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.getStockDetail(params.row.id);
                      },
                    },
                  },
                  "库存"
              );
              enableOrDisable = h(
                  "Button",
                  {
                    props: {
                      type: "warning",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.lower(params.row);
                      },
                    },
                  },
                  "下架"
              );
            }
            return h("div", [
              h(
                  "Button",
                  {
                    props: {
                      type: "info",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.editGoods(params.row);
                      },
                    },
                  },
                  "编辑"
              ),
              showEditStock,
              enableOrDisable,
            ]);
          },
        },
      ],
      data: [], // 表單數据
      total: 0, // 表單數据总數
      warnNum: 0 //库存警告數量
    };
  },
  methods: {
    init() {
      // 初始化數据
      this.getDataList();
    },
    // 添加商品
    addGoods() {
      this.$router.push({name: "goods-operation"});
    },
    // 编辑商品
    editGoods(v) {
      this.$router.push({name: "goods-operation-edit", query: {id: v.id}});
    },

    //批量操作
    handleDropdown(v) {
      //批量上架
      if (v == "uppers") {
        this.uppers();
      }
      //批量下架
      if (v == "lowers") {
        this.lowers();
      }
      //批量删除商品
      if (v == "deleteAll") {
        this.deleteAll();
      }
      //批量设置物流模板
      if (v == "batchShipTemplate") {
        this.batchShipTemplate();
      }
    },
    // 获取库存詳情
    getStockDetail(id) {
      getGoodsSkuListDataSeller({goodsId: id, pageSize: 1000}).then((res) => {
        if (res.success) {
          this.updateStockModalVisible = true;
          this.stockAllUpdate = undefined;
          this.stockList = res.result.records;
        }
      });
    },
    // 上傳數据
    handleUpload(file) {
      this.file = file;
      this.upload();
      return false;
    },
    /**
     * 上傳文件
     */
    async upload() {
      let fd = new FormData();
      fd.append("files", this.file);
      this.spinShow = false
      let res = await uploadGoodsExcel(fd);
      if (res.success) {
        this.spinShow = true
        this.$Message.success("导入成功")
      }
    },
    openImportGoods() {
      this.importModal = true
    },
    async exportGoods() {
      downLoadGoods()
          .then((res) => {
            const blob = new Blob([res], {
              type: "application/vnd.ms-excel;charset=utf-8",
            });
            //对於<a>標签，只有 Firefox 和 Chrome（内核） 支持 download 属性
            //IE10以上支持blob但是依然不支持download
            if ("download" in document.createElement("a")) {
              //支持a標签download的瀏覽器
              const link = document.createElement("a"); //创建a標签
              link.download = "商品批量导入模板.xls"; //a標签添加属性
              link.style.display = "none";
              link.href = URL.createObjectURL(blob);
              document.body.appendChild(link);
              link.click(); //執行下载
              URL.revokeObjectURL(link.href); //释放url
              document.body.removeChild(link); //释放標签
            } else {
              navigator.msSaveBlob(blob, fileName);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },
    // 更新库存
    updateStock() {
      let updateStockList = this.stockList.map((i) => {
        let j = {skuId: i.id, quantity: i.quantity};
        if (this.stockAllUpdate) {
          j.quantity = this.stockAllUpdate;
          j.quantity = this.stockAllUpdate;
        }
        return j;
      });
      updateGoodsSkuStocks(updateStockList).then((res) => {
        if (res.success) {
          this.updateStockModalVisible = false;
          this.$Message.success("更新库存成功");
          this.getDataList();
        }
      });
    },
    // 改变頁碼
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataList();
      this.clearSelectAll();
    },
    // 改变頁數
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getDataList();
    },
    // 搜索
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getDataList();
    },
    // 重置搜索條件
    handleReset() {
      this.searchForm = {};
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      // 重新加载數据
      this.getDataList();
    },
    // 清除多選
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    // 添加選中项
    changeSelect(e) {
      this.selectList = e;
      this.selectCount = e.length;
    },
    //保存物流模板信息
    saveShipTemplate() {
      this.$Modal.confirm({
        title: "確認设置物流模板",
        content: "您確認要设置所選的 " + this.selectCount + " 个商品的物流模板?",
        loading: true,
        onOk: () => {
          let ids = [];
          this.selectList.forEach(function (e) {
            ids.push(e.id);
          });
          // 批量设置物流模板
          batchShipTemplate(this.shipTemplateForm).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("物流模板设置成功");
              this.clearSelectAll();
              this.getDataList();
            }
            this.shipTemplateModal = false;
          });
        },
      });
    },
    //批量设置物流模板
    batchShipTemplate() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您還未選擇要设置物流模板的商品");
        return;
      }
      this.getShipTempList();
      let data = [];
      this.selectList.forEach(function (e) {
        data.push(e.id);
      });
      this.shipTemplateForm.goodsId = data;
      this.shipTemplateModal = true;
    },
    // 获取商品列表數据
    getDataList() {
      this.loading = true;
      // 带多條件搜索參數获取表單數据
      getGoodsListDataSeller(this.searchForm).then((res) => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records;
          this.total = res.result.total;
          //根据店铺id查询店铺预警库存數
          this.selectsWarningStock(this.data[0].storeId);
        }
      });
    },
    // 获取物流模板
    getShipTempList() {
      API_Shop.getShipTemplate().then((res) => {
        if (res.success) {
          this.logisticsTemplate = res.result;
        }
      });
    },
    //下架商品
    lower(v) {
      this.$Modal.confirm({
        title: "確認下架",
        content: "您確認要下架 " + v.goodsName + " ?",
        loading: true,
        onOk: () => {
          let params = {
            goodsId: v.id,
          };
          lowGoods(params).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("下架成功");
              this.getDataList();
            }
          });
        },
      });
    },
    //批量下架
    lowers() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您還未選擇要下架的商品");
        return;
      }
      this.$Modal.confirm({
        title: "確認下架",
        content: "您確認要下架所選的 " + this.selectCount + " 个商品?",
        loading: true,
        onOk: () => {
          let ids = [];
          this.selectList.forEach(function (e) {
            ids.push(e.id);
          });
          let params = {
            goodsId: ids.toString(),
          };
          // 批量上架
          lowGoods(params).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("下架成功");
              this.clearSelectAll();
              this.getDataList();
            }
          });
        },
      });
    },
    //批量删除商品
    deleteAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您還未選擇要删除的商品");
        return;
      }
      this.$Modal.confirm({
        title: "確認删除",
        content: "您確認要删除所選的 " + this.selectCount + " 个商品?",
        loading: true,
        onOk: () => {
          let ids = [];
          this.selectList.forEach(function (e) {
            ids.push(e.id);
          });
          let params = {
            goodsId: ids.toString(),
          };
          // 批量删除
          deleteGoods(params).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.clearSelectAll();
              this.getDataList();
            }
          });
        },
      });
    },
    //批量上架
    uppers(v) {
      if (this.selectCount <= 0) {
        this.$Message.warning("您還未選擇要上架的商品");
        return;
      }
      this.$Modal.confirm({
        title: "確認上架",
        content: "您確認要上架所選的 " + this.selectCount + " 个商品?",
        loading: true,
        onOk: () => {
          let ids = [];
          this.selectList.forEach(function (e) {
            ids.push(e.id);
          });
          let params = {
            goodsId: ids.toString(),
          };
          // 批量上架
          upGoods(params).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("上架成功");
              this.clearSelectAll();
              this.getDataList();
            }
          });
        },
      });
    },
    upper(v) {
      this.$Modal.confirm({
        title: "確認上架",
        content: "您確認要上架 " + v.goodsName + " ?",
        loading: true,
        onOk: () => {
          let params = {
            goodsId: v.id,
          };
          upGoods(params).then((res) => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("上架成功");
              this.getDataList();
            }
          });
        },
      });
    },
    //根据店铺id去查询店铺的预警库存
    selectsWarningStock(id) {
      let params = {
        storeId: id
      }
      selectsWarningStock(params).then((res) => {
        this.warnNum = res.result
      });
    },
    //查看低库存商品
    viewWarnData() {
      this.searchForm.warnNum = this.warnNum;
      getWarnData(this.searchForm).then((res) => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records;
          this.total = res.result.total;
        }
      });
    }


  },
  mounted() {
    this.init();
    this.accessToken.accessToken = this.getStore("accessToken");
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/table-common.scss";
</style>
